package com.light.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.light.common.dto.savespuinfo.*;
import com.light.common.enums.PublishStatusEnum;
import com.light.common.exception.RRException;
import com.light.common.pojo.ESPojo;
import com.light.common.utils.PageUtils;
import com.light.common.utils.Query;
import com.light.common.utils.R;
import com.light.common.vo.WareStockVO;
import com.light.gulimall.product.dao.*;
import com.light.gulimall.product.entity.*;
import com.light.gulimall.product.feign.CouponRemoteServiceClient;
import com.light.gulimall.product.feign.ESRemoteServiceClient;
import com.light.gulimall.product.feign.WareRemoteServiceClient;
import com.light.gulimall.product.service.*;
import com.light.gulimall.product.vo.SpuInfoVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoService spuInfoService;

    /**
     * feign客户端
     */
    @Autowired
    private CouponRemoteServiceClient couponRemoteServiceClient;

    /**
     * pms_spu_info spu信息
     */
    @Autowired
    private SpuInfoDao spuInfoDao;

    /**
     * pms_spu_info_desc spu信息介绍
     */
    @Autowired
    private SpuInfoDescDao spuInfoDescDao;

    /**
     * default_img  spu图片
     */
    @Autowired
    private SpuImagesDao spuImagesDao;

    /**
     * pms_product_attr_value spu属性值
     */
    @Autowired
    private ProductAttrValueDao productAttrValueDao;

    /**
     * pms_sku_info sku信息
     */
    @Autowired
    private SkuInfoDao skuInfoDao;

    /**
     * pms_sku_images sku图片
     */
    @Autowired
    private SkuImagesDao skuImagesDao;

    @Autowired
    private SkuSaleAttrValueDao skuSaleAttrValueDao;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private WareRemoteServiceClient wareRemoteServiceClient;

    @Autowired
    private ESRemoteServiceClient esRemoteServiceClient;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 新增商品
     *
     * @param spuInfo 商品信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//要改成分布式事务
    public void saveSpuInfo(SaveSpuInfoDTO spuInfo) {
        try {
            //1.保存pms_spu_info
            Long id = this.saveInfo(spuInfo);
            spuInfo.setSpuId(id);

            //2.保存pms_spu_info_desc
            spuInfoService.saveSpuInfoDesc(spuInfo, id);

            //3.保存pms_spu_images
            spuInfoService.saveSpuImages(spuInfo, id);

            //5.保存pms_product_attr_value
            spuInfoService.saveProductAttrValue(spuInfo, id);

            //保存sku相关信息
            spuInfoService.saveSkuInfo(spuInfo, id);
        } catch (Exception e) {
            log.error("product模块保存商品信息出现异常！原因：", e);
            throw new RRException("product模块保存商品信息出现异常");
        }

        //远程调用coupon模块，保存sms_spu_bounds sms_sku_ladder  sms_sku_full_reduction sms_member_price
        R r = couponRemoteServiceClient.saveCouponReleaseInfo(spuInfo);
        if (r.get("code").equals(500)) {
            throw new RRException("远程调用coupon模块保存优惠券数据错误！");
        }

    }

    public void saveSkuInfo(SaveSpuInfoDTO skuInfo, Long id) {
        long catalogId = skuInfo.getCatalogId();
        long brandId = skuInfo.getBrandId();
        List<Skus> skus = skuInfo.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            for (Skus sku : skus) {
                //6.TODO 保存pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(id);
                skuInfoEntity.setCatalogId(catalogId);
                skuInfoEntity.setBrandId(brandId);
                skuInfoEntity.setSkuDesc(String.join(",", sku.getDescar()));
                List<String> imgUrls = sku.getImages().stream().filter(images -> images.getDefaultImg() == 1).map(Images::getImgUrl).collect(Collectors.toList());
                skuInfoEntity.setSkuDefaultImg(String.join(",", imgUrls));
                skuInfoEntity.setSaleCount(0L);
                skuInfoDao.insert(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                //7.保存pms_sku_images
                List<Images> images = sku.getImages();
                if (!CollectionUtils.isEmpty(images)) {
                    for (Images image : images) {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        BeanUtils.copyProperties(image, skuImagesEntity);
                        skuImagesEntity.setSkuId(skuId);
                        skuImagesDao.insert(skuImagesEntity);
                    }
                }
                //8.保存pms_sku_sale_attr_value
                List<Attr> attrs = sku.getAttr();
                if (!CollectionUtils.isEmpty(attrs)) {
                    for (Attr attr : attrs) {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                        skuSaleAttrValueEntity.setSkuId(skuId);
                        skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                        skuSaleAttrValueDao.insert(skuSaleAttrValueEntity);
                    }
                }
                sku.setSkuId(skuId);
            }
        }
    }

    public void saveProductAttrValue(SaveSpuInfoDTO skuInfo, Long id) {
        ArrayList<ProductAttrValueEntity> productAttrValueEntities = new ArrayList<>();
        for (BaseAttrs baseAttr : skuInfo.getBaseAttrs()) {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            BeanUtils.copyProperties(baseAttr, productAttrValueEntity);
            productAttrValueEntity.setSpuId(id);
            productAttrValueEntity.setAttrId(baseAttr.getAttrId());
            productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
            productAttrValueEntities.add(productAttrValueEntity);
        }
        productAttrValueDao.insert(productAttrValueEntities);
    }

    public void saveSpuImages(SaveSpuInfoDTO skuInfo, Long id) {
        SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
        spuImagesEntity.setSpuId(id);
        spuImagesEntity.setImgUrl(String.join(",", skuInfo.getImages()));
        spuImagesDao.insert(spuImagesEntity);
    }

    public void saveSpuInfoDesc(SaveSpuInfoDTO skuInfo, Long id) {
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(id);
        spuInfoDescEntity.setDecript(String.join(",", skuInfo.getDecript()));
        spuInfoDescDao.insert(spuInfoDescEntity);
    }

    public Long saveInfo(SaveSpuInfoDTO skuInfo) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(skuInfo, spuInfoEntity);
        spuInfoEntity.setCatalogId(skuInfo.getCatalogId());
        spuInfoEntity.setBrandId(skuInfo.getBrandId());
        spuInfoEntity.setCreateTime(new Date());
        spuInfoDao.insert(spuInfoEntity);
        return spuInfoEntity.getId();
    }

    /**
     * 根据条件分页查询spu信息
     *
     * @param params 查询条件
     * @return 分页返回结果
     */
    @Override
    public PageUtils queryByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();

        String key = ((String) params.get("key"));
        if (!StringUtils.isBlank(key)) {
            spuInfoEntityQueryWrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isBlank(status)) {
            spuInfoEntityQueryWrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isBlank(brandId)) {
            spuInfoEntityQueryWrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isBlank(catelogId)) {
            spuInfoEntityQueryWrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                spuInfoEntityQueryWrapper
        );

        return new PageUtils(page);

    }

    @Override
    public void up(Long spuId) {
        //查询当前spuId对应的所有sku信息
        //一个spu可以对应多个sku，将某一个spu下的所有sku批量上架
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        //attrs 查询当前spu下所有商品可以被检索的信息
        List<ProductAttrValueEntity> attrValueEntities = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = attrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<ESPojo.Attr> attrs = productAttrValueDao.filterNeedSearchAttrs(attrIds).stream().map(productAttrValueEntity -> {
            ESPojo.Attr attr = new ESPojo.Attr();
            BeanUtils.copyProperties(productAttrValueEntity, attr);
            return attr;
        }).collect(Collectors.toList());

        //hasStock 远程调用库存服务
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> map = null;
        try {
            List<WareStockVO> wareStockVOS = wareRemoteServiceClient.queryWareStock(skuIds);
            map = wareStockVOS.stream().collect(Collectors.toMap(WareStockVO::getSkuId, WareStockVO::getHasStock));
        } catch (Exception e) {
            log.error("调用库存服务出现异常:", e);
            return;
        }


        //封装es信息
        List<ESPojo> esPojos = new ArrayList<>();
        for (SkuInfoEntity infoEntity : skus) {
            ESPojo esPojo = new ESPojo();
            BeanUtils.copyProperties(infoEntity, esPojo);
            //skuPrice->price
            esPojo.setSkuPrice(infoEntity.getPrice());
            //skuImg->skuDefaultImg
            esPojo.setSkuImg(infoEntity.getSkuDefaultImg());
            esPojo.setSpuId(String.valueOf(infoEntity.getSpuId()));

            //库存
            esPojo.setHasStock(map.get(infoEntity.getSkuId()));
            //hotScore
            esPojo.setHotScore(0L);
            //设置品牌信息
            brandService.getBrandInfoById(infoEntity.getBrandId(), esPojo);
            //设置分类信息
            categoryService.getCateInfoById(infoEntity.getCatalogId(), esPojo);
            esPojo.setAttrs(attrs);

            ESPojo apply = esPojo;
            esPojos.add(apply);
        }


        //调用ES保存商品上架接口
        R r = esRemoteServiceClient.productStatusUp(esPojos);
        if ((Integer) r.get("code") == 0) {
            //批量修改状态为上架
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setPublishStatus(PublishStatusEnum.UP.getCode());
            update(spuInfoEntity, new QueryWrapper<SpuInfoEntity>().eq("id", spuId));
        } else {
            //TODO 重试机制
        }
    }

    @Override
    public SpuInfoVO getSpuInfo(Long skuId) {
        return spuInfoDao.getSpuInfo(skuId);
    }

}